/**
 * 
 */
package com.young.common.config;

import com.young.common.exception.BaseException;
import com.young.common.util.CommonConstants;
import com.young.common.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 异常处理
 * @author rookie
 *
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

	private Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		PrintWriter pw = null;
		try {
			logger.error("[全局异常处理] Exception URL={}", request.getRequestURL(), ex);
			response.setCharacterEncoding(CommonConstants.CHARSET);//编码
			response.setContentType("application/json; charset=utf-8");
			pw = response.getWriter();
			/*if (!(request.getHeader("accept")!=null && request.getHeader("accept").indexOf("application/json") > -1 ||
					request.getHeader("X-Requested-With")!=null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {//如果不是异步请求
				//pw.write("error");//返回错误页
			}else{
				Result result = null;
				if(ex instanceof BaseException){
					result.setCode(((BaseException) ex).getCode());
					result.setInfo(((BaseException) ex).getInfo());
				}else{
					result = Result.build(Result.CodeEnum.SYSTEM_EXCEPTION);
				}
				pw.write(result.toString());
			}*/
			Result result = null;
			if(ex instanceof BaseException){
				result = new Result(((BaseException)ex).getCode(), ((BaseException) ex).getInfo());
			}else{
				result = Result.build(Result.CodeEnum.SYSTEM_EXCEPTION);
			}
			pw.write(result.toString());
		} catch (IOException e) {
			logger.error("[全局异常处理] 响应流写入异常", e);
		} catch (Exception e) {
			logger.error("[全局异常处理] 异常处理过程中发生异常!!!", e);
		} finally {
			try{
				if(pw!=null)
					pw.close();
			}catch (Exception e) {
				logger.error("[全局异常处理] 关闭PrintWriter异常", e);
			}
		}
		return modelAndView;
	}

}
